﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcShop.Extensions.Encryption
{
    public class AntiForgeryToken
    {
        #region ==== Initializer ====
        /// <summary>
        /// 对称加密类的构造函数
        /// </summary>
        /// <param name="salt">任意的Guid</param>
        public AntiForgeryToken()
        {
            Ticks = generateTicks();
            this._symmetric = new SymmetricMethod();
        }
        #endregion

        #region ==== Fields ====
        private SymmetricMethod _symmetric;
        public static readonly string TicksName = "southShopAntiForgeryTicks";
        public static readonly string TokenName = "southShopAntiForgeryToken";
        #endregion

        #region ==== Properties ====
        public long Ticks
        {
            get;
            set;
        }
        /// <summary>
        /// 获得加密的票据
        /// </summary>
        public string Value
        {
            get
            {
                return EncrypTick(Ticks);
            }
        }
        #endregion

        #region ==== Methods ====
        /// <summary>
        /// 加密票据
        /// </summary>
        /// <param name="ticks">Utc票据</param>
        /// <returns>加密的票据</returns>
        private string EncrypTick(long ticks)
        {
            var salt = Guid.NewGuid();
            return this._symmetric.Encrypto(string.Concat(salt, ticks)); ;
        }

        /// <summary>
        /// 解密Utc票据
        /// </summary>
        /// <param name="source">原字符串</param>
        /// <returns>字符串类型的Utc票据</returns>
        public string DecrypTick(string source)
        {
            var dpass = this._symmetric.Decrypto(source);
            var dpLength = dpass.Length;
            if (dpLength > 36)
            {
                return dpass.Substring(36, dpLength - 36);
            }
            return null;
        }

        /// <summary>
        /// 获取Utc票据，辅助方法
        /// </summary>
        /// <returns></returns>
        public long generateTicks()
        {
            return DateTime.UtcNow.Ticks;
        }
        #endregion
    }
}
